package com.order.config;

import com.aaa.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableResourceServer // 代表是一个资源服务器
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled=true)
public class MyResourceConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 所有的找资源  进行操作的时候  都要 认证之后才能进行访问
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()

                .exceptionHandling().accessDeniedHandler(getAceessDefinedHandle())
                //.access("@RbacConfig.hasPermission(request,authentication)")
                .and()
                .csrf().disable();
    }


    /**
     * 配置一个tokenStore
     */
    @Bean
    public TokenStore getTokenStore(){
        return new JwtTokenStore(getConvert());
    }

    /**
     * 构建 令牌
     * @return
     */
    @Bean
    public JwtAccessTokenConverter getConvert(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("test");
        return  jwtAccessTokenConverter;
    }


    @Bean
    public AccessDeniedHandler getAceessDefinedHandle(){
        return (request, response, accessDeniedException) -> {
            Result result = Result.accessDefined(null);
            printJsonData(result,response);
        };
    }



    public void printJsonData(Result result, HttpServletResponse response) throws IOException {
        // 以json的形式 传递除去
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(result);
        // 响应到前端
        response.setContentType("application/json;charset=utf8");
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
